package handler

import (
	"fmt"
	"github.com/zeromicro/go-zero/rest/httpx"
	"io/ioutil"
	"log"
	"net/http"
	"strings"
	"zg4_month_exam/user/api/internal/logic"
	"zg4_month_exam/user/api/internal/svc"
	"zg4_month_exam/user/api/internal/types"
	"zg4_month_exam/user/common"
)

func UploadHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		switch r.FormValue("choose") {
		case "1":
			file, headers, err := r.FormFile("path")
			if err != nil {
				log.Printf("Error when try to get file: %v", err)
				return
			}
			//获取上传文件的类型
			if strings.HasSuffix(headers.Filename, "/jpg") && strings.HasSuffix(headers.Filename, "/mp4") {
				log.Printf("只允许文本，图片，视频文件文件")
				return
			}
			data, err := ioutil.ReadAll(file)
			if err != nil {
				log.Printf("Read file error: %v", err)
				return
			}
			fn := headers.Filename
			path := "./internal/video/" + fn
			err = ioutil.WriteFile(path, data, 0666)
			if err != nil {
				log.Printf("Write file error: %v", err)
				return
			}
			r.Form.Set("name", fn)
			r.Form.Set("path", path)
		case "3":
			//阿里云上传
			file, headers, err := r.FormFile("path")
			if err != nil {
				log.Printf("Error when try to get file: %v", err)
				return
			}
			defer file.Close()
			if headers.Size > 5*1024*1024 {
				fmt.Println("超过5M的文件不允许上传")
				return
			}
			//如果文件名中包含png,jpg就判断文件是否超过2M，超过不往下执行。
			if strings.Contains(headers.Filename, "png") && strings.Contains(headers.Filename, "jpg") {
				if headers.Size > 2*1024*1024 {
					fmt.Println("图片过大，请尝试其他图片")
					return
				}
			}
			//调用阿里云
			path := common.AliFile(headers)
			r.Form.Set("path", path)
			r.Form.Set("name", headers.Filename)
		}
		var req types.Uploadrequest
		if err := httpx.Parse(r, &req); err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
			return
		}

		l := logic.NewUploadLogic(r.Context(), svcCtx)
		resp, err := l.Upload(&req)
		if err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
		} else {
			httpx.OkJsonCtx(r.Context(), w, resp)
		}
	}
}
